{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 优化 ONNX 模型的实用工具\n",
    "\n",
    "参考：[optimize.py](https://github.com/microsoft/onnxscript/blob/main/tools/optimize.py)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import onnx\n",
    "import onnx.inliner\n",
    "import onnxscript\n",
    "\n",
    "def optimize(\n",
    "    input_file_name: str, output_file_name: str|None=None,\n",
    ") -> None:\n",
    "    \"\"\"使用 `onnxscript` 库将 ONNX 模型文件转换为 Python 脚本\"\"\"\n",
    "    model = onnx.load(input_file_name, load_external_data=False)\n",
    "    model = onnxscript.optimizer.optimize(model)\n",
    "    model = onnx.inliner.inline_local_functions(model)\n",
    "    # Optimize again in case inlining created new opportunities.\n",
    "    model = onnxscript.optimizer.optimize(model)\n",
    "\n",
    "    # If output file name is not provided, use the input file name with .py extension\n",
    "    if output_file_name is None:\n",
    "        base_name = os.path.splitext(input_file_name)[0]  # Remove extension\n",
    "        output_file_name = base_name + \"_opt.onnx\"\n",
    "\n",
    "    onnx.save(model, output_file_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_file_name = \"/media/pc/data/board/arria10/lxw/tasks/tools/npuusertools/models/xmdemo/adas/_opt.onnx\"\n",
    "optimize(input_file_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
